package com.cjg.Class;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class demo08 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class<?> aClass = Class.forName("com.cjg.Class.Student");

        //相当于创建一个无参构造器
//        Student student= (Student) aClass.newInstance();
//        System.out.println(student);


        // 通过构造器创建对象
//        Constructor<?> c = aClass.getDeclaredConstructor(String.class, int.class, int.class);
//        Object 老爷 = c.newInstance("老爷", 0, 1);
//        System.out.println(老爷);
        //通过反射调用方法
//        Student s1= (Student) aClass.newInstance();
//        Method setAge = aClass.getDeclaredMethod("setAge", int.class);
//        Object invoke = setAge.invoke(s1, 2);
//        System.out.println(s1.getAge());

        //通过反射调用属性
        Student s2= (Student) aClass.newInstance();
        Field age = aClass.getDeclaredField("age");

        //设置只能设置public属性 需要关闭安全监测才能设置private属性
        age.setAccessible(true);

        age.set(s2,100);
        System.out.println(s2.getAge());

    }
}
